<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="buyHtAccount">购买互通账号</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="jqtCpHtOrderAccountList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="唯一ID" align="center" prop="id" v-if="false" />
        <el-table-column label="企业微信订单ID" align="center" prop="orderId" show-overflow-tooltip/>
        <el-table-column label="账号类型" align="center" prop="type">
          <template #default="scope">
            <el-tag v-if="scope.row.type == 1">基础账号</el-tag>
            <el-tag v-if="scope.row.type == 2" type="success">互通账号</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="status">
          <template #default="scope">
            <el-tag v-if="scope.row.status == 0">未激活</el-tag>
            <el-tag v-if="scope.row.status == 1" type="success">已激活</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="开通月数" align="center" prop="months" width="180" />
        <el-table-column label="激活用户" align="center" prop="nameRemark" />
        <el-table-column label="激活时间" align="center" prop="activeTime" width="180" />
        <el-table-column label="过期时间" align="center" prop="expireTime" width="180" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="绑定互通用户" placement="top">
              <el-button link type="primary" @click="handleUpdate(scope.row)" v-hasPermi="['bus:jqtCpHtOrderAccount:edit']">绑定互通用户</el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改企业互通订单账号对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="jqtCpHtOrderAccountFormRef" :model="formData" :rules="rulesHt" label-width="80px">
        <el-form-item label="互通用户" prop="htUserId">
          <el-select v-model="formData.htUserId" placeholder="请选择互通用户">
            <el-option v-for="item in htUsers" :key="item.id" :label="item.nameRemark" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>


    <!-- 购买互通账号 -->
    <el-dialog :title="dialogBuy.title" v-model="dialogBuy.visible" width="700px" append-to-body>
      <jqtCpHtUserBuy v-if="dialogBuy.visible" ref="jqtCpHtUserBuyRef"></jqtCpHtUserBuy>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitBuyForm">支付完成</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="JqtCpHtOrderAccount" lang="ts">
import {
  listJqtCpHtOrderAccount,
  getJqtCpHtOrderAccount,
  delJqtCpHtOrderAccount,
  addJqtCpHtOrderAccount,
  updateJqtCpHtOrderAccount,
  bindHtUser
} from '@/api/bus/jqtCpHtOrderAccount';
import { JqtCpHtOrderAccountVO, JqtCpHtOrderAccountQuery, JqtCpHtOrderAccountForm } from '@/api/bus/jqtCpHtOrderAccount/types';
import jqtCpHtUserBuy from '@/views/bus/jqtCpHtUserBuy/index.vue'
import { getHtUsers } from '@/api/bus/jqtCpHtUser';
import { JqtCpHtUserVO } from '@/api/bus/jqtCpHtUser/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
// 创建 ref 来引用子组件实例
const jqtCpHtUserBuyRef = ref(null)

const jqtCpHtOrderAccountList = ref<JqtCpHtOrderAccountVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const jqtCpHtOrderAccountFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
const dialogBuy = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: JqtCpHtOrderAccountForm = {
  id: undefined,
  remark: undefined,
  userId: undefined,
  htOrderId: undefined,
  orderId: undefined,
  activeCode: undefined,
  wxUserId: undefined,
  type: undefined,
  status: undefined,
  activeHtUser: undefined,
  activeWxUserId: undefined,
  activeTime: undefined,
  expireTime: undefined
}
const data = reactive<PageData<JqtCpHtOrderAccountForm, JqtCpHtOrderAccountQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userId: undefined,
    htOrderId: undefined,
    orderId: undefined,
    activeCode: undefined,
    wxUserId: undefined,
    type: undefined,
    status: undefined,
    activeHtUser: undefined,
    activeWxUserId: undefined,
    activeTime: undefined,
    expireTime: undefined,
    params: {
    }
  },
  rules: {
    remark: [
      { required: true, message: "备注不能为空", trigger: "blur" }
    ],
    userId: [
      { required: true, message: "用户id不能为空", trigger: "blur" }
    ],
    htOrderId: [
      { required: true, message: "互通订单表id不能为空", trigger: "blur" }
    ],
    orderId: [
      { required: true, message: "企业微信订单id不能为空", trigger: "blur" }
    ],
    activeCode: [
      { required: true, message: "账号码，订单类型为购买账号时不能为空", trigger: "blur" }
    ],
    wxUserId: [
      { required: true, message: "企业续期成员userid，订单类型为续期账号时，返回该字段。返回加密的userid不能为空", trigger: "blur" }
    ],
    type: [
      { required: true, message: "账号类型：1:基础账号，2:互通账号不能为空", trigger: "change" }
    ],
    status: [
      { required: true, message: "状态(0.未激活 1.已激活)不能为空", trigger: "change" }
    ],
    activeHtUser: [
      { required: true, message: "激活用户id不能为空", trigger: "blur" }
    ],
    activeWxUserId: [
      { required: true, message: "激活企业微信用户id不能为空", trigger: "blur" }
    ],
    activeTime: [
      { required: true, message: "激活时间不能为空", trigger: "blur" }
    ],
    expireTime: [
      { required: true, message: "过期时间不能为空", trigger: "blur" }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

export interface BindHtUserBo {
  // 互通用户id
  htUserId: string | number;
  // 互通账号ID
  accountId: string | number;
}
const formData = reactive<BindHtUserBo>({
  htUserId: undefined,
  accountId: undefined
})
const rulesHt = {
  htUserId: [{ required: true, message: '请选择互通用户', trigger: 'blur' }],
  accountId: [{ required: true, message: '请选择互通账号ID', trigger: 'blur' }],
}


/** 查询企业互通订单账号列表 */
const getList = async () => {
  loading.value = true;
  const res = await listJqtCpHtOrderAccount(queryParams.value);
  jqtCpHtOrderAccountList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
  dialogBuy.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  jqtCpHtOrderAccountFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: JqtCpHtOrderAccountVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 修改按钮操作 */
const handleUpdate = async (row?: JqtCpHtOrderAccountVO) => {
  reset();
  await getHtUsersData();
  const _id = row?.id || ids.value[0]
  formData.accountId = _id;
  dialog.visible = true;
  dialog.title = "激活互通账号";
}

/** 提交按钮 */
const submitForm = () => {
  jqtCpHtOrderAccountFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (formData.accountId) {
        await bindHtUser(formData).finally(() =>  buttonLoading.value = false);
        proxy?.$modal.msgSuccess("操作成功");
        dialog.visible = false;
        await getList();
      }
    }
  });
}

onMounted(() => {
  getList();
  getHtUsersData();
});

const buyHtAccount = async () => {
  // proxy.$router.push({
  //   name: 'CpHtUserBuy'
  // })
  dialogBuy.title = "购买互通账号";
  dialogBuy.visible = true;
}
//提交购买表单
const submitBuyForm = async () => {
  //校验购买完毕
  if (jqtCpHtUserBuyRef.value) {
    // 调用子组件的 getData 方法
    const data = await jqtCpHtUserBuyRef.value.getOrderPayStatusInfo()
    if(data === '1'){
      proxy?.$modal.msgSuccess("支付完成");
      dialogBuy.visible = false;
      await getList();
    }else{
      proxy?.$modal.msgError("暂未支付完成");
    }
  }
}

/**
 * 获取互通用户列表
 */
const htUsers = ref<JqtCpHtUserVO[]>([]);
const getHtUsersData = async () => {
  const res = await getHtUsers();
  htUsers.value = res.data;
}
</script>
